using System;
using System.Security;
using System.Security.Cryptography;
using System.Net;
using System.Collections;
using System.Xml;
using System.Text;

using WebServer;

namespace WebServer.Modules
{
	/// <summary>
	/// Provides a list of encryption hash-types.
	/// </summary>
	public enum CryptoHashType
	{
		/// <summary>
		/// MD5 encryption.
		/// </summary>
		MD5,
		/// <summary>
		/// SHA1 encryption.
		/// </summary>
		SHA1
	}

	/// <summary>
	/// Exposes methods to simplify encryption of strings.
	/// </summary>
	[CoreModule("Cryptography", typeof(Cryptography), CoreModulePriority.High)]
	public class Cryptography
	{
		private static MD5CryptoServiceProvider _MD5HashProvider;
		private static byte[] _MD5HashBuffer;

		private static SHA1CryptoServiceProvider _SHA1HashProvider;
		private static byte[] _SHA1HashBuffer;

		private static void Start()
		{
			if (_MD5HashProvider == null)
				_MD5HashProvider = new MD5CryptoServiceProvider();

			if (_SHA1HashProvider == null)
				_SHA1HashProvider = new SHA1CryptoServiceProvider();

			if (_MD5HashBuffer == null)
				_MD5HashBuffer = new byte[256];

			if (_SHA1HashBuffer == null)
				_SHA1HashBuffer = new byte[256];
		}

		/// <summary>
		/// Encrypts the specified string value into the MD5-hash string value equivilent.
		/// </summary>
		/// <param name="plainText">Text to encrypt.</param>
		/// <returns>MD5-encrypted hash-code string value.</returns>
		public static string MD5Hash( string plainText )
		{
			if( _MD5HashProvider == null )
				_MD5HashProvider = new MD5CryptoServiceProvider( );

			if( _MD5HashBuffer == null )
				_MD5HashBuffer = new byte[256];

			int length = Encoding.Default.GetBytes( plainText, 0, plainText.Length > 256 ? 256 : plainText.Length, _MD5HashBuffer, 0 );
			byte[] hashed = _MD5HashProvider.ComputeHash( _MD5HashBuffer, 0, length );

			return BitConverter.ToString( hashed );
		}


		/// <summary>
		/// Encrypts the specified string value into the SHA1-hash string value equivilent.
		/// </summary>
		/// <param name="plainText">Text to encrypt.</param>
		/// <returns>SHA1-encrypted hash-code string value.</returns>
		public static string SHA1Hash( string plainText )
		{
			if( _SHA1HashProvider == null )
				_SHA1HashProvider = new SHA1CryptoServiceProvider( );

			if( _SHA1HashBuffer == null )
				_SHA1HashBuffer = new byte[256];

			int length = Encoding.Default.GetBytes( plainText, 0, plainText.Length > 256 ? 256 : plainText.Length, _SHA1HashBuffer, 0 );
			byte[] hashed = _SHA1HashProvider.ComputeHash( _SHA1HashBuffer, 0, length );

			return BitConverter.ToString( hashed );
		}
	}
}